package com.tools.cleanmaster.controller;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.MediaStore;

import com.tools.cleanmaster.BuildConfig;
import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.bean.ApkFileInfo;
import com.tools.cleanmaster.manager.ApkFileManager;
import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.item.TrashItem;
import com.tools.cleanmaster.utils.LogHelper;

import java.io.File;

/**
 * Created by lianzhan on 16/2/22.
 */
public class ApkScanner extends FileMediaStoreScanner {
    private static final String SQL_SECLECTION_DATA_POSTFIX = "_data like \"%\" || ?";

    public ApkScanner(Context context, TrashHandler handler) {
        super(context, handler);
    }

    @Override
    protected void doScan(int increaseProgress) {
        scanMediaApk(increaseProgress);
    }

    @Override
    protected TrashType getTrashType() {
        return TrashType.APK_FILE;
    }

    @SuppressLint("NewApi")
    private void scanMediaApk(int increaseProgress) {
        Cursor cursor = null;
        long startTime = 0;
        if (BuildConfig.DEBUG_LOG) {
            startTime = System.currentTimeMillis();
        }
        try {
            ContentResolver contentResolver = CleanApplication.getInstance().getContentResolver();
            cursor = contentResolver.query(MediaStore.Files.getContentUri(DB_NAME_EXTERNAL),
                    new String[]{
                            MediaStore.Files.FileColumns.DATA
                    }, SQL_SECLECTION_DATA_POSTFIX, new String[]{
                            ".apk"
                    }, null);
            if (cursor == null) {
                return;
            }
            int count = cursor.getCount();
            LogHelper.v(SUB_TAG, "doScan, scanMediaApk cursor count=" + count);
            if (count == 0) {
                mTrashHandler.updateProgress(increaseProgress, null);
                return;
            }
            int index = 0;
            while (cursor.moveToNext()) {
                if (mStopRequested) {
                    LogHelper.v(SUB_TAG, "doScan, scanMediaApk mStopRequested, in while return");
                    return;
                }
                String path = cursor.getString(0);
                int progressFile = calculateProgress(increaseProgress, index, count);
                mTrashHandler.updateProgress(progressFile, path);
                index++;
                File file = new File(path);
                if (file.exists()) {
                    boolean isSkippedFolder = false;
                    for (String root : mSdCardRootDirs) {
                        for (String p : APK_PATH_SKIPPED) {
                            if (path.startsWith(new File(root, p).getAbsolutePath())) {
                                isSkippedFolder = true;
                                break;
                            }
                        }
                        if (isSkippedFolder) {
                            break;
                        }
                    }
                    if (!isSkippedFolder) {
                        createTrashItemApk(file, path);
                    }
                }
            }
        } catch (Exception e) {
                LogHelper.e(SUB_TAG, "scanMediaLog", e);
            return;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
            LogHelper.v(SUB_TAG, "doScan, scanMediaApk end! time = "
                    + (System.currentTimeMillis() - startTime));
    }

    private TrashItem createTrashItemApk(File f, String absolutePath) {
        TrashItem trash = null;
        ApkFileInfo apkInfo = ApkFileManager.getInstance().getApkInfo(absolutePath);
        if (apkInfo != null) {
            trash = apkInfo.createApkFileItem();
        }
        LogHelper.i(SUB_TAG, "createTrashItemApk trash=" + trash);
        if (trash == null) {
            return null;
            // trash = parseApkFile(f);
        }
        mScanSize += trash.size;
        if (!mStopRequested) {
            mTrashesData.putTrash(TrashType.APK_FILE, trash);
        }
        LogHelper.v(SUB_TAG, "[trash_unless] filePath:" + absolutePath);
        return trash;
    }

    // file matcher
    private static final String[] APK_PATH_SKIPPED = {
            ".android_secure", "OpenRecovery", "TitaniumBackup", "TitaniumBackup",
            "AndroidOptimizer/systembackup/"
    };
}
